<template>
  <div>
    <van-sticky>
      <van-nav-bar
        title="商品详情"
        left-text=""
        left-arrow
        @click-left="onClickLeft"
      />
    </van-sticky>
    <!--商品 -->
    <div class="card">
      <img :src="productData.masterImg" alt="" />
    </div>

    <!-- ---------------------------------------------------------------- -->
    <div class="boss">
      <div class="price">
        <span> <em>¥</em>{{ productData.price }}</span>
      </div>
      <h2>{{ productData.title }}</h2>
    </div>
    <div class="num">
      <span>购买数量</span>
      <van-stepper
        v-model="value"
        theme="round"
        button-size="22"
        disable-input
      />
    </div>
    <div class="specification">
      <van-cell title="用户评价（99）" is-link value="评价" />
    </div>
    <div class="specification margin_bottom">
      <van-cell title="商家评分" is-link value="5.0分" />
    </div>
    <!-- ------------------------------footer---------------------------------- -->
    <van-action-bar>
      <van-action-bar-icon icon="cart-o" text="购物车" @click="goCart" />
      <van-action-bar-button
        type="warning"
        text="加入购物车"
        @click="addCart"
      />
      <van-action-bar-button
        type="danger"
        text="立即购买"
        @click="showPopup1"
      />
      <van-popup v-model:show="show1" position="bottom"
        ><van-password-input
          :value="value1"
          :focused="showKeyboard"
          info="请输入支付密码"
          :error-info="errorInfo"
          @focus="showKeyboard = true" />
        <!-- 数字键盘 -->
        <van-number-keyboard
          v-model="value1"
          :show="showKeyboard"
          @blur="showKeyboard = false"
      /></van-popup>
    </van-action-bar>
  </div>
</template>

<script>
import {
  NavBar,
  Sticky,
  Toast,
  ActionBar,
  ActionBarIcon,
  ActionBarButton,
  Stepper,
  Cell,
  PasswordInput,
  NumberKeyboard,
  Popup,
} from "vant";
import { useRouter, useRoute } from "vue-router";
import { ref ,watch} from "vue";

export default {
  setup() {
    const onClickLeft = () => {
      router.go(-1);
    };
    const product = ref([]);
    const onClickRight = () => Toast("按钮");
    const router = useRouter();
    const route = useRoute();

    const productData = ref([]);

    const value = ref(1);

    const id = route.params.id;

    const show1 = ref(false);
    const value1 = ref("");
    const showKeyboard = ref(true);
    const errorInfo = ref("");

    const getData = function () {
      fetch("http://2107.wqdp.com.cn/index/market?count=15")
        .then((response) => response.json())
        .then((res) => {
          product.value = res.result;
          productData.value = product.value.filter((item) => item.id == id)[0];
          console.log(productData.value);
        });
    };

    const goCart = function () {
      console.log(123);
      router.push("/cart");
    };

    const addCart = function () {
      const stickdetail = {
        id: productData.value.id,
        title: productData.value.title,
        url: productData.value.masterImg,
        num: value.value,
        price: productData.value.price,
      };

      let stick = JSON.parse(sessionStorage.getItem("cart"));

      if (stick) {
        if (stick.some((el) => el.id === stickdetail.id)) {
          let _index = stick.findIndex((elm) => {
            console.log(id);
            return elm.id == id;
          });

          let count = parseInt(stick[_index].num);

          count += value.value;

          stick[_index].num = count;
          console.log(1);
          // console.log(stick[_index].num);
          //找不到直接添加
        } else {
          console.log(2);
          stick.push(stickdetail);
        }
      } else {
        stick = [];
        stick.push(stickdetail);
        console.log(3);
      }
      Toast.success("加入购物车成功");
      sessionStorage.setItem("cart", JSON.stringify(stick));
    };
    const showPopup1 = () => {
       if (localStorage.getItem("token")) {
        fetch("http://2107.wqdp.com.cn/users/token", {
          method: "POST",
          body: JSON.stringify({
            token: localStorage.getItem("token"),
          }),
          headers: {
            "content-type": "application/json",
          },
        })
          .then((response) => response.json())
          .then((res) => {
            //判断token是否正确
            if (res.status == 0) {
              show1.value = true;
            } else {
              Toast.fail("用户信息错误");
              localStorage.removeItem("token");
              router.push("/login");
            }
          });
      } else {
        router.push("/login");
      }
    };

    getData();

    watch(value1, (newVal) => {
      if (newVal.length === 6) {
        fetch("http://2107.wqdp.com.cn/users/token", {
          method: "POST",
          body: JSON.stringify({
            token: localStorage.getItem("token"),
            zfmm: newVal,
          }),
          headers: {
            "content-type": "application/json",
          },
        })
          .then((response) => response.json())
          .then((res) => {
            //密码正确往订单中传输数据
            if (res.status == 0) {
              Toast.success("支付成功");
              //传输数据变量
              const stickdetail = {
                id: productData.value.id,
                title: productData.value.title,
                url: productData.value.masterImg,
                num: value.value,
                price: productData.value.price,
              };
              //获取本地存储
              let stick = JSON.parse(sessionStorage.getItem("cart"));
              //判定是否有本地储存
              if (stick) {
                //如果有找到id 重新赋值num
                if (stick.some((el) => el.id === productData.value.id)) {
                  let _index = stick.findIndex((elm) => elm.id == productData.value.id);
                  let count = parseInt(stick[_index].num);
                  count += parseInt(stick[_index].num);
                  stick[_index].num = count;
                  //找不到直接添加
                } else {
                  
                  stick.push(stickdetail);
                  
                }
              } else {
                //没有本地存储的话直接设置
                stick = [];
                stick.push(stickdetail);
              }
              sessionStorage.setItem("cart", JSON.stringify(stick));
              router.push("/order");
            } else {
              Toast.fail("支付密码错误");
              value1.value = "";
            }
          });
      } else {
        errorInfo.value = "";
      }
    });

    return {
      onClickLeft,
      onClickRight,
      getData,
      productData,
      value,
      addCart,
      goCart,
      show1,
      value1,
      showKeyboard,
      errorInfo,
      showPopup1,
    };
  },

  components: {
    vanNavBar: NavBar,
    vanSticky: Sticky,
    vanActionBar: ActionBar,
    vanActionBarIcon: ActionBarIcon,
    vanActionBarButton: ActionBarButton,
    vanStepper: Stepper,
    vanCell: Cell,
    vanPasswordInput: PasswordInput,
    vanNumberKeyboard: NumberKeyboard,
    vanPopup: Popup,
  },

  computed: {},

  mounted() {},

  methods: {},
};
</script>

<style lang="less" scoped>
/deep/.van-nav-bar .van-icon {
  color: #000;
  font-size: 20px;
}

.boss {
  padding: 20px;
  background: #fff;
  margin-bottom: 20px;
  .price {
    color: #fd6c00;
    // margin-top: 20px;
    margin-bottom: 10px;
    span {
      font-size: 22px;
      em {
        font-size: 12px;
      }
    }
  }
  h2 {
    font-size: 18px;
  }
}
.card {
  width: 100%;
  height: 300px;
  background: #fff;
  img {
    height: 100%;
    display: block;
    margin: auto;
  }
}
.num {
  padding: 5px 10px 5px 25px;
  display: flex;
  border-radius: 10px;
  background: #fff;
  /deep/ .van-stepper {
    margin-top: 10px;
  }
  /deep/.van-stepper--round .van-stepper__minus {
    border: 1px solid #ccc;
    color: #ccc;
  }
  /deep/.van-stepper--round .van-stepper__plus {
    border: 1px solid #ccc;
    color: #ccc;
    background: #fff;
  }
  span {
    margin-right: 170px;
    font-size: 18px;
    line-height: 50px;
  }
}
.specification {
  height: 60px;
  background: #fff;
  border-radius: 10px;
  padding: 10px;
  margin-top: 10px;
  margin-bottom: 20px;
  span {
    font-size: 16px;
    display: inline-block;
    margin-right: 20px;
  }
  .xuan {
    float: right;
    font-size: 22px;
    color: #666;
    line-height: 60px;

    b {
      font-size: 18px;
      font-weight: normal;
    }
  }
}
.margin_bottom {
  margin-bottom: 70px;
  /deep/.van-cell__value {
    span {
      color: orangered;
    }
  }
}
/deep/.van-popup--bottom {
  padding-top:50px;
  height: 500px;
}
</style>
